﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace ECommon
{
    /// <summary>
    /// 单例工厂
    /// </summary>
    /// <typeparam name="T">单例泛型函数</typeparam>
    public static partial class SingletonFactory
    {
        /// <summary>
        /// 构建一个泛型实例
        /// </summary>
        /// <typeparam name="T">实例泛型</typeparam>
        /// <param name="pms">构造函数的参数</param>
        /// <returns>泛型实例</returns>
        public static T CreateInstance<T>(params object[] pms) where T : class
        {
            string name = typeof(T).FullName;
            object obj = null;
            if (_instanceDict.ContainsKey(name))
            {
                obj = _instanceDict[name];
            }
            if (obj == null)
            {
                lock (_singletonLock)
                {
                    if (obj == null)
                    {
                        obj = Make<T>(pms);
                        if (obj != null)
                        {
                            _instanceDict[name] = obj;
                        }
                    }
                }
            }
            return obj as T;
        }
        /// <summary>
        /// 实例集合
        /// </summary>
        private static Dictionary<string, object> _instanceDict = new Dictionary<string, object>();
        /// <summary>
        /// 单例锁
        /// </summary>
        private static object _singletonLock = new object();

        /// <summary>
        /// 构建一个泛型实例
        /// </summary>
        /// <typeparam name="T">实例泛型</typeparam>
        /// <param name="pms">构造函数的参数</param>
        /// <returns>泛型实例</returns>
        private static T Make<T>(params object[] pms) where T : class
        {
            // 获取类型信息
            Type type = typeof(T);
            List<Type> types = new List<Type>();
            foreach (object obj in pms)
            {
                types.Add(pms.GetType());
            }
            // 获取私有构造函数（参数为 string）
            ConstructorInfo constructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types.ToArray(), null);
            if (constructor != null)
            {
                // 使用构造函数创建实例
                return constructor.Invoke(pms) as T;
            }
            else
            {
                return null;
            }
        }
    }
}
